<template>
  <a-card>
    <div class="container">

      <div class="left">
        <a-spin :spinning="loading">
          <div>
            <a-input-search
              v-model="searchValue"
              style="margin-bottom: 8px;width: 70%"
              placeholder="搜索"
              @change="searchTreeNode"
            />
          </div>
          <div style="overflow:auto;height:600px">
            <a-tree
              :tree-data="treeData"
              default-expand-all
              checkable
              class="tree-div-select-hidden"
              :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
              @select="onSelect"
              @check="onCheck"
            >
            </a-tree>

          </div>
        </a-spin>
      </div>
      <div class="right">
        <div id="m">
          <MapTencentCom
            ref="map"
            :zoom="16"
            :pitch="30"
            :callback="true"
            :isShowBtn="false"
            @callback="callBack"
            @confirm="confirm"
          />
        </div>
      </div>

    </div>

  </a-card>
</template>

<script>
import MapTencentCom from '@/views/visualization/map/MapTencent_com.vue'
import { findDefaultTreeGeopoint } from '@/api/correction/crc_geopoint'
export default {

  data () {
    return {
      initMap: false,
      treeData: [],
      cloneTreeData: [],
      loading: false,
      searchValue: ''
    }
  },
  components: {
    MapTencentCom
  },
  watch: {
    initMap () {
      document.getElementById('drawStart').click()
      console.log('drawLayer', this.$refs.map.drawLayer)
      this.$refs.map.drawLayer.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT)
      this.$refs.map.drawLayer.setSelectable(true)
      this.setGeopoints()
    }
  },
  async created () {
    this.initTreeData()
  },
  methods: {
    setSlot (treeData) {
      if (treeData.geopoints && treeData.geopoints != null) {
        treeData.disableCheckbox = false
      } else {
        treeData.disableCheckbox = true
      }
      if (treeData.children && treeData.children.length > 0) {
        treeData.children.forEach(child => {
          if (child && child.children) {
            this.setSlot(child)
          }
        })
      }
    },

    searchTreeNode (e) {
      const value = e.target.value
      // this.treeData.forEach(treeData => {
      //   this.filter(treeData, value)
      // })
      this.filter(this.treeData, value)
      if (value == '') {
        this.treeData = JSON.parse(JSON.stringify(this.cloneTreeData)) //cloneTreeData 接口返回深拷贝的数据
      }
    },
    filter (nodes, query) {
      // 条件就是节点的title过滤关键字
      let predicate = function (node) {
        if (node.name.indexOf(query) > -1) {
          return true
        } else {
          return false
        }
      }
      if (!(nodes && nodes.length)) {
        return []
      }
      let newChildren = []
      for (let node of nodes) {
        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        if (predicate(node)) {
          newChildren.push(node)
          node.children = this.filter(node.children, query)
        } else {
          newChildren.push(...this.filter(node.children, query))
        }
      }
      this.treeData = newChildren //this.treeData接口返回的数组
      return newChildren.length ? newChildren : []
    },

    async initTreeData () {
      this.loading = true
      const res = await findDefaultTreeGeopoint().finally(() => {
        this.loading = false
      })
      if (res.code == 0) {
        console.log('查询数据成功', res.data)
        this.treeData = res.data
        if (this.treeData) {
          this.treeData.forEach(treeData => {
            this.setSlot(treeData)
          })
        }
        this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
      } else {
        this.$message('查询数据失败')
      }
    },
    callBack (map) {
      console.log('callBack')
      this.$refs.map.showDraw()
      console.log('地图信息', map)
    },
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },

    findTreeDataByKey (treeData, keys, result) {
      if (keys.includes(treeData.id)) {
        result.push(treeData)
      }
      if (treeData.children && treeData.children.length > 0) {
        treeData.children.forEach(child => {
          if (child && child.children) {
            this.findTreeDataByKey(child, keys, result)
          }
        })
      }
    },

    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      // 查询对应的树节点数据
      const checkTreeArrays = []
      this.treeData.forEach(treeData => {
        this.findTreeDataByKey(treeData, checkedKeys, checkTreeArrays)
      })
      if (checkTreeArrays && checkTreeArrays.length > 0) {
        const areaArrays = []
        checkTreeArrays.forEach(selectArea => {
          if (selectArea.geopoints) {
            const areas = JSON.parse(selectArea.geopoints)
            if (areas && areas.length > 0) {
              for (const area of areas) {
                areaArrays.push(area)
              }
            }
          }
        })
        this.setGeopoints(areaArrays)
      } else {
        this.setGeopoints([])
      }
    },
    setGeopoints (areas) {
      // const areas = JSON.parse('[[{"lat":28.704839796469003,"lng":115.94895926727179},{"lat":28.674584703490407,"lng":115.94941109331376},{"lat":28.674716841134753,"lng":115.97380960645603},{"lat":28.704443498585515,"lng":115.9730565663101}]]')
      const geopoints = []
      const points = []
      for (let i = 0; i < areas.length; i++) {
        geopoints.push({
          paths: []
        })
        for (let j = 0; j < areas[i].length; j++) {
          points.push(areas[i][j].lat + ',' + areas[i][j].lng)
          geopoints[i].paths.push(new TMap.LatLng(areas[i][j].lat, areas[i][j].lng))
        }
      }
      console.log('drawPolygon', this.$refs.map.drawPolygon)
      this.$refs.map.drawPolygon.setGeometries(geopoints)
      console.log(geopoints[0].paths[0].lat, geopoints[0].paths[0].lng)
      this.$refs.map.setCenter(...this.getPointsCenter(points))
    },
    getPointsCenter (points) {
      const pointNum = points.length
      let X = 0; let Y = 0; let Z = 0
      for (let i = 0; i < points.length; i++) {
        if (points[i] === '') {
          continue
        }
        const point = points[i].split(',')
        let lat, lng, x, y, z
        lat = parseFloat(point[0]) * Math.PI / 180
        lng = parseFloat(point[1]) * Math.PI / 180
        x = Math.cos(lat) * Math.cos(lng)
        y = Math.cos(lat) * Math.sin(lng)
        z = Math.sin(lat)
        X += x
        Y += y
        Z += z
      }
      X = X / pointNum
      Y = Y / pointNum
      Z = Z / pointNum

      const tmpLng = Math.atan2(Y, X)
      const tmpLat = Math.atan2(Z, Math.sqrt(X * X + Y * Y))

      return [tmpLat * 180 / Math.PI, tmpLng * 180 / Math.PI]
    },
    confirm (drawPolygon) {
      if (
        drawPolygon.geometries != null &&
        drawPolygon.geometries.length > 0
      ) {
        const areas = []
        for (let r = 0; r < drawPolygon.geometries.length; r++) {
          const points = []
          for (
            let x = 0;
            x < drawPolygon.geometries[r].paths.length;
            x++
          ) {
            const item = drawPolygon.geometries[r].paths[x]
            points.push({ lat: item.lat, lng: item.lng })
          }
          areas.push(points)
          this.info.geopoints = JSON.stringify(areas)
          this.openModel = true
        }
      } else {
        this.$message.warning('请选择范围')
      }
    }
  }

}
</script>

<style lang="scss" scoped>
  #m {
    position: sticky;
  }
  .container {
    display: flex;
  }
  .left, .right {
    margin: 10px;
  }
  .left {
    width: 20%;
    min-height: 600px;
    overflow: auto;
  }
  .right {
    width: 80%;
    min-height: 600px;
  }

</style>
